﻿using System;
using System.Drawing;

namespace SalesSys.Comm.Utility
{
    public class ValidateImg
    {
        /// <summary>
        /// 创建一个内容基本的验证码图片生成器
        /// </summary>
        /// <param name="HotPixeLv">干扰线级别，0~6,越大干扰越多，0:无，1:背景点，2:背景线，3:前景线，4:后曲线，5前曲线，6同色</param>
        public ValidateImg(DayOfWeek hotPixeLv,int width=64,int height=28)
        {
            imgHeight = height;
            imgWidth = width;
            var lv = (int)hotPixeLv;
            //
            hotPixelNum = imgWidth / 20 * lv;
            //
            fontSize = imgHeight - 12;
            randAngle = 8 * lv;
        }

        ///  <summary>  
        ///  生成随机码  
        ///  </summary>  
        ///  <param  name="length">随机码个数</param>  
        ///  <returns></returns>  
        public string CreateRandomCode(int length)
        {
            int rand;
            char code;
            string randomcode = String.Empty;

            //生成一定长度的验证码  
            System.Random random = new Random();
            for (int i = 0; i < length; i++)
            {
                rand = random.Next();

                if (rand % 3 == 0)
                {
                    code = (char)('A' + (char)(rand % 26));
                }
                else
                {
                    code = (char)('0' + (char)(rand % 10));
                }

                randomcode += code.ToString();
            }
            return randomcode;
        }

        Random rand = new Random();
        // 定义随机颜色列表  
        Color[] mainColors = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };

        private Color bgColor = Color.AliceBlue;
        // 定义随机字体字体  
        string[] font = { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial", "宋体" };

        private FontStyle defFontStyle = FontStyle.Bold;
        private float fontSize = 16;
        //字符串对齐
        StringFormat strFormat = new StringFormat(StringFormatFlags.NoClip);
        int randAngle = 45;     //随机转动角度范围

        private int imgHeight = 28;  //图片高度,
        private int imgWidth = 64;   //图片宽度
        //干扰线数量
        private int hotPixelNum = 50;


        ///  <summary>  
        ///  创建随机码图片  
        ///  </summary>  
        ///  <param  name="randomcode">随机码</param>  
        public void CreateImage(string randomcode,string savePath)
        {
            var mapHeight = imgHeight;
            var mapWidth = (int)(randomcode.Length * fontSize);
            using (Bitmap map = new Bitmap(mapWidth, mapHeight))//创建图片背景，设置其长宽  
            {
                CreateImage(randomcode, map);
                map.Save(savePath, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
        }
        public byte[] CreateImage(string randomcode)
        {
            var mapHeight = imgHeight;
            var mapWidth = (int)(randomcode.Length * fontSize);
            using (Bitmap map = new Bitmap(mapWidth, mapHeight))//创建图片背景，设置其长宽  
            {
                CreateImage(randomcode, map);
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                map.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                return ms.ToArray();
            }
        }
         Bitmap CreateImage(string randomcode,Bitmap map)
        {
            using (Graphics graph = Graphics.FromImage(map))
            {
                graph.Clear(bgColor);
                graph.DrawRectangle(new Pen(Color.Black, 0), 0, 0, map.Width - 1, map.Height - 1);//画一个边框    
                // 生成背景噪点  
                DrawHotPixel(map, graph);
                char[] chars = randomcode.ToCharArray();//拆散字符串成单字符数组     
                for (int i = 0; i < chars.Length; i++)
                {
                    var nowChar = chars[i].ToString();
                    DrawChar(graph, nowChar);
                }
            }
            return map;
        }
        private void DrawChar(Graphics graph, string nowChar)
        {
            var format = StrAlign();
            int cindex = rand.Next(7);
            int findex = rand.Next(5);

            Font f = new System.Drawing.Font(font[findex], fontSize, defFontStyle);
            Brush b = new System.Drawing.SolidBrush(mainColors[cindex]);
            Point dot = new Point(11, 11); // 括号内数值越大，字符间距越大  
            //验证码旋转，防止机器识别  
            float angle = rand.Next(-randAngle, randAngle); // 转动的度数，如果将0改为-randAngle，那么旋转角度为-45度～45度  

            graph.TranslateTransform(dot.X, dot.Y);
            graph.RotateTransform(angle);
            graph.DrawString(nowChar, f, b, 2, 6, format); // 第4、5个参数控制左、上间距  
            graph.RotateTransform(-angle);
            graph.TranslateTransform(2, -dot.Y);
        }


        private StringFormat StrAlign()
        {
            strFormat.Alignment = StringAlignment.Center;
            strFormat.LineAlignment = StringAlignment.Center;
            return strFormat;
        }

        public void DrawHotPixel(Bitmap map, Graphics graph)
        {
            Pen blackPen = new Pen(Color.Blue, 0);

            for (int i = 0; i < hotPixelNum; i++)
            {
                int x = rand.Next(0, map.Width);
                int y = rand.Next(0, map.Height);
                int x2 = rand.Next(0, map.Width);
                int y2 = rand.Next(0, map.Height);
                graph.DrawLine(blackPen, x, y, x2, y2);
            }
        }
    }  
}
